/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: serialstd_win.cpp,v 1.2 2008-02-04 08:09:22 amaula Exp $
 *
 */
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

#ifdef LINUX_OS
#include <sys/uio.h>
#include <sys/io.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <poll.h>
#endif

#include "serialstd.hpp"
#include "owndebug.h"

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CSerialStd::CSerialStd(int aId, const std::string &aBusName)
  : CSerial(aId, aBusName),
    iPortfd(0),
    iOldPortSet(NULL),
    iNewPortSet(NULL)
{
}
//*****************************************************************************

CSerialStd::~CSerialStd()
{
#ifdef LINUX_OS
  if ( iOldPortSet ) delete iOldPortSet;
  if ( iNewPortSet ) delete iNewPortSet;
#endif

}
//*****************************************************************************

ASRobo::Drivers::Bus::EBusStatus CSerialStd::Open(void)
{
#ifdef LINUX_OS
  int speed;
  dPrint(6,"Opening new Bus; CSerialStd, ID: %04x, name: '%s'",
	 iBusID, iBusName.c_str());

  iPortfd = open(iPortname.c_str(), O_RDWR | O_SYNC , S_IRUSR | S_IWUSR );
  if (iPortfd < 0) {
    dPrint(2,"Failed to open port \"%s\"!",
	   iPortname.c_str());
    return KBusStatusError;
  }

  // FIXME: This is not checked, so be sure to use correct constants!
  speed = iPortspeed;

  // Allocate memory
  iOldPortSet = new struct termios;
  iNewPortSet = new struct termios;

  // Get old.
  tcgetattr( iPortfd, iOldPortSet);

  // Do new.
  if( tcgetattr( iPortfd, iNewPortSet ) < 0 ) {
    dPrint(2, "Failed to read settings for serial port! (%s)",
	   iPortname.c_str());
    return KBusStatusError;
  }

  cfmakeraw( iNewPortSet );

  // Set minimum characters to 2
  iNewPortSet->c_cc[VMIN] = 0; // Minimum 2 chars
  iNewPortSet->c_cc[VTIME] = 5; // Max 5 deciseconds chars

  cfsetispeed( iNewPortSet, speed );
  cfsetospeed( iNewPortSet, speed );

  if( tcsetattr( iPortfd, TCSAFLUSH,
		 iNewPortSet ) < 0 ) {
    dPrint(2,"Failed to set new settings on serial port! (%s)",
	   iPortname.c_str());
    return KBusStatusError;
  }

  tcflush(iPortfd, TCIOFLUSH);

  dPrint(4,"Successfully opened Serial device '%s'", iPortname.c_str());
#endif
  return KBusStatusOK;
}
//*****************************************************************************

int CSerialStd::Read(unsigned char *buffer, int buffer_size)
{
#ifdef LINUX_OS
  int lastread;
  lastread = read(iPortfd, buffer, buffer_size);

  if (lastread < 0) {
    dPrint(3,"Error reading from device! (%s)",
	   iPortname.c_str());
    lastread = -1;
  }

  return lastread;
#else
  return 0;
#endif
}
//*****************************************************************************

int CSerialStd::Write(const unsigned char *buffer, int buffer_size)
{
#ifdef LINUX_OS
  int wb;

  wb = write(iPortfd, buffer, buffer_size);

  //  tcdrain(iPortfd); // FIXME: Wait until all data transmitted?

  return wb;
#else
  return 0;
#endif
}
//*****************************************************************************

ASRobo::Drivers::Bus::EBusStatus CSerialStd::WaitToRead(const int aTimeout_ms)
{
#ifdef LINUX_OS
  int r;
  struct pollfd p = { iPortfd, POLLIN, 0 };
  EBusStatus status = KBusStatusError;

  // Do poll
  r = poll(&p, 1, aTimeout_ms);

  // Check result
  if (r > 0) {
    // Accept only POLLIN events, other will cause error.
    if (p.revents & POLLIN) {
      status = KBusStatusOK;
    }

  } else if (r == 0) {
    // In case of zero value, assume timeout.
    status = KBusStatusTimeout;

  }
  return status;
#else
  return KBusStatusError;
#endif
}
//*****************************************************************************

ASRobo::Drivers::Bus::EBusStatus CSerialStd::WaitToWrite(const int aTimeout_ms)
{
#ifdef LINUX_OS
  int r;
  struct pollfd p = { iPortfd, POLLOUT, 0 };
  EBusStatus status = KBusStatusError;

  // Do poll
  r = poll(&p, 1, aTimeout_ms);

  // Check result
  if (r > 0) {
    // Accept only POLLIN events, other will cause error.
    if (p.revents & POLLOUT) {
      status = KBusStatusOK;
    }

  } else if (r == 0) {
    // In case of zero value, assume timeout.
    status = KBusStatusTimeout;

  }

  return status;
#else
  return KBusStatusError;
#endif
}
//*****************************************************************************

ASRobo::Drivers::Bus::EBusStatus CSerialStd::Close(void)
{
  EBusStatus error = KBusStatusError;

#ifdef LINUX_OS
  if((tcsetattr(iPortfd, TCSAFLUSH, iOldPortSet) )!=-1) {
    if((close(iPortfd)) != -1) {
      error = KBusStatusOK;
    }
  }
#endif

  return error;
}
//*****************************************************************************

int CSerialStd::Flush(void)
{
  int error = -1;

#ifdef LINUX_OS
  if (!tcflush(iPortfd, TCIOFLUSH)) {
    error = 0;
  }
#endif

  return error;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
